﻿using System;
using System.IO;
using XCI.Core;
using XCI.Helper;

namespace XCI.Windows
{
    public partial class FrmUpgradeConfig : BaseForm
    {
        private readonly AppHandler handler = new AppHandler();
        private AppSetting appSetting;
        private WebApiConfig apiConfig;

        public FrmUpgradeConfig()
        {
            InitializeComponent();
        }

        private void LoadConfig()
        {
            var config = UpgradeConfig.Get();
            editCatalog.Text = config.Catalog;
            try
            {
                editPassword.Text = EncryptHelper.SymmetricDecrypt(config.Password, EncryptHelper.SecretKey);
            }
            catch
            {
                // ignored
            }
        }

        private void SaveConfig()
        {
            var config = UpgradeConfig.Get();
            config.Catalog = editCatalog.Text;
            config.Password = EncryptHelper.SymmetricEncrypt(editPassword.Text, EncryptHelper.SecretKey);
            UpgradeConfig.Save();
        }

        private void UpgradeForm_Load(object sender, EventArgs e)
        {
            appSetting = handler.LoadAppSetting();
            editId.Text = appSetting.Id;
            editName.Text = appSetting.Name;

            apiConfig = appSetting.Server;
            if (appSetting.FileServer != null && !string.IsNullOrEmpty(appSetting.FileServer.BaseUrl))
            {
                apiConfig = appSetting.FileServer;
            }
            editBaseUrl.Text = apiConfig.BaseUrl;
            LoadConfig();
        }

        private async void btnUpload_Click(object sender, EventArgs e)
        {
            var password = editPassword.Text.Trim();
            var catalog = editCatalog.Text.Trim();

            #region 校验

            if (string.IsNullOrEmpty(editId.Text.Trim()))
            {
                MessageBoxHelper.ShowWarn("请配置应用标识");
                return;
            }

            if (string.IsNullOrEmpty(editBaseUrl.Text.Trim()))
            {
                MessageBoxHelper.ShowWarn("请配置服务器");
                return;
            }

            if (string.IsNullOrEmpty(password))
            {
                MessageBoxHelper.ShowWarn("请输入上传密码");
                return;
            }

            if (string.IsNullOrEmpty(catalog))
            {
                MessageBoxHelper.ShowWarn("请选择更新包目录");
                return;
            }

            #endregion

            if (!Directory.Exists(catalog))
            {
                MessageBoxHelper.ShowWarn("更新包目录不存在");
                return;
            }
            if (MessageBoxHelper.ShowMessageYesNo("确定要上传当前更新包吗？") != System.Windows.Forms.DialogResult.Yes)
            {
                return;
            }

            try
            {
                Loading.Show();
                var zipFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"tmp", $"{StringHelper.Guid()}.zip");
                IOHelper.CreateDirectoryByPath(zipFilePath);
                ZipHelper.CompressDirectory(zipFilePath, catalog);
                var data = SMap.New.Set("password", EncryptHelper.AESEncrypt(password));
                var client = handler.CreateFileWebApiClient(apiConfig);
                var result = await client.UploadAsBoolResultAsync<FileModel>("/upgrade/upload", zipFilePath, data);
                IOHelper.DeleteFile(zipFilePath);
                Loading.Hide();
                if (result.Fail)
                {
                    MessageBoxHelper.ShowError(result.Msg);
                    return;
                }

                SaveConfig();
                MessageBoxHelper.ShowMessage("更新包上传成功");
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Loading.Hide();
                MessageBoxHelper.ShowError("更新包上传失败\n" + DebugHelper.BuildAllMessage(ex));
            }
            finally
            {
                Loading.Hide();
            }
        }

        private async void btnTest_Click(object sender, EventArgs e)
        {
            await WinFormHelper.WebApiClientTest(apiConfig, Loading);
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                editCatalog.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}